#coding: utf-8
import timeit
import MySQLdb
import urllib2
import base64
from HTMLParser import HTMLParser
from tasy.data_source.settings import *
database_config=INTERFACE_DATABASES['image']


def get_con():
    conn=MySQLdb.connect(host=database_config['HOST'],port=database_config['PORT'],user=database_config['USER'],passwd=database_config['PASSWORD'],db=database_config['DB'],charset="utf8")
    return conn

#删除html标记
def remove_tag(html):
    html=html.strip()
    html=html.strip('\n')
    result=[]
    parse=HTMLParser()
    parse.handle_data=result.append
    parse.feed(html)
    parse.close()
    return "".join(result)

#获得图片的地址
def get_pic_address(pic_id,pic_ext_name):
    if pic_id>2632512:
        pic_short_path="%s%s%s%s%s%s%s%s%s%s%s" %(PIC_ADDRESS,"new/",SIZE,"/",get_path(pic_id),"Img",str(pic_id),"_",SIZE,".",pic_ext_name)
    else:
        pic_short_path="%s%s%s%s%s%s%s%s%s%s" %(PIC_ADDRESS,SIZE,"/",get_path(pic_id),"Img",str(pic_id),"_",SIZE,".",pic_ext_name)
    return pic_short_path

def get_path(id):
    tmp=str(id)
    length=len(tmp)
    path="%s%s%s%s" %(tmp[length-2:],"/",tmp[length-4:length-2],"/")
    return path

def get_json_object(group=(),list=[]):
    json_object={}
    json_object['title']=group[2]
    json_object['gid']=group[1]
    json_object['shortName']=group[4]
    json_object['time']=group[5].strftime('%Y-%m-%d %H:%M:%S')
    json_object['size']=len(list)
    if len(list)>0:
        json_object['img']=list[0]['img']
    else:
        json_object['img']=''
    return json_object

def get_picturegroup_list(create_time,  count, channel=None):
    try:
        json_array=[]
        conn=get_con()
        cursor = conn.cursor()
        if not channel:
            groupsql="select id,cate_id,picgroup_name,picgroup_desc,picgroup_short_name,picgroup_ctime from picgroups where picgroup_ctime>'%s' and status>0 limit 0,%s" %(create_time,count)
        else:
            catlsql="select id,cate_name,cate_type from categorys where id=%s" % channel
            cursor.execute(catlsql)
            catlog=cursor.fetchone()
            if catlog:
                cate_type=catlog[2]
                if cate_type==0:
                    catlsql="select id from categorys where cate_rela like '%|"+str(channel)+"|%'"
                    cursor = conn.cursor()
                    cursor.execute(catlsql)
                    catlog_id=cursor.fetchall()
                    catid_conditon=[]
                    for cid in catlog_id:
                        catid_conditon.append("cate_id="+str(cid[0]))
                    catid=" or ".join(catid_conditon)
                else:
                    catid="cate_id=%s"%channel
            groupsql="select id,cate_id,picgroup_name,picgroup_desc,picgroup_short_name,picgroup_ctime from picgroups where picgroup_ctime>='%s' and (%s) and status>0 limit 0,%s" %(create_time,catid,count)
        cursor.execute(groupsql)
        group_lst=cursor.fetchall()
        for group in group_lst:
            if not group[4]:
                continue
            picsql="select id,pic_name,pic_desc,extension, pic_priority from pics where picgroup_id=%s order by pic_priority desc,id desc" % group[0]
            cursor.execute(picsql)
            pic_list=cursor.fetchall()
            list=[]
            for row in pic_list:
                requst_url=GET_SHORT_ADDRESS % base64.encodestring(get_pic_address(row[0],row[3]))
                data=urllib2.urlopen(requst_url).read()
                list.append({'title':row[1],"desc":remove_tag(row[2]),"img":data,"source":get_pic_address(row[0],row[3])})
            json_object=get_json_object(group,list)
            json_object['imgList']=list
            json_array.append(json_object)

    except Exception as e:
        print e
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()
    return json_array

def get_picturegroup(gid):
    try:
        json_array=[]
        groupsql="select id,cate_id,picgroup_name,picgroup_desc,picgroup_short_name,picgroup_ctime from picgroups where id=%s" % gid
        conn=get_con()
        cursor=conn.cursor()
        cursor.execute(groupsql)
        groupinfo=cursor.fetchone()
        if groupinfo:
            piclistsql="select id,pic_name,pic_desc,extension, pic_priority from pics where picgroup_id=%s order by PIC_PRIORITY desc,id desc" %gid
            cursor.execute(piclistsql)
            list=[]
            pic_list=cursor.fetchall()
            for row in pic_list:
                url=GET_SHORT_ADDRESS % base64.encodestring(get_pic_address(row[0],row[3]))
                data=urllib2.urlopen(url).read()
                source=get_pic_address(row[0],row[3])
                list.append({'title':row[1],"desc":remove_tag(row[2]),"img":data,"source":get_pic_address(row[0],row[3])})
            json_object=get_json_object(groupinfo,list)
            json_object['imgList']=list
            json_array.append(json_object)
        if cursor:
            cursor.close()
        if conn:
            conn.close()
    except Exception as e:
        print e
    return json_array

if __name__=="__main__":
#    #a=get_picturegroup_list('2008-08-10 11:16:37',2,914406)
#    #a1=get_picturegroup_list('2012-05-24 15:00:00',2)
#    b=get_picturegroup(349478)
#    #print a
#    print b
    t = timeit.Timer('get_picturegroup(349478)', "from __main__ import get_picturegroup")
    print t.repeat(1, 1)
    print 'end'
    print timeit.Timer('get_con()', "from __main__ import get_con").repeat(1, 1)
